<template>
  <div class="tab-header flex items-center bg-white border-b border-gray-200">
    <!-- 标签页列表 -->
    <div class="tab-list flex-1 flex overflow-x-auto">
      <div
        v-for="tab in tabStore.tabs"
        :key="tab.id"
        :class="[
          'tab-item',
          {
            'active': tab.id === tabStore.activeTabId,
            'unsaved': tab.unsaved
          }
        ]"
        @click="setActiveTab(tab.id)"
        @contextmenu="handleTabContextMenu($event, tab)"
      >
        <!-- 标签页图标 -->
        <el-icon class="tab-icon">
          <component :is="getTabIcon(tab)" />
        </el-icon>

        <!-- 标签页标题 -->
        <span class="tab-title" :title="getTabTooltip(tab)">
          {{ tab.title }}
        </span>

        <!-- 未保存指示器 -->
        <div v-if="tab.unsaved" class="unsaved-indicator"></div>

        <!-- 关闭按钮 -->
        <el-button
          v-if="tab.closable !== false"
          link
          size="small"
          class="tab-close"
          @click.stop="closeTab(tab.id)"
        >
          <el-icon><Close /></el-icon>
        </el-button>
      </div>

      <!-- 新建标签页按钮 -->
      <div class="new-tab-btn" @click="openNewTabMenu">
        <el-icon><Plus /></el-icon>
      </div>
    </div>

    <!-- 标签页操作按钮 -->
    <div class="tab-actions flex items-center space-x-1 px-2">
      <el-dropdown @command="handleTabAction" trigger="click">
        <el-button link size="small">
          <el-icon><MoreFilled /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="closeOthers" :disabled="tabStore.tabs.length <= 1">
              关闭其他标签页
            </el-dropdown-item>
            <el-dropdown-item command="closeAll" :disabled="tabStore.tabs.length === 0">
              关闭所有标签页
            </el-dropdown-item>
            <el-dropdown-item divided command="saveAll" :disabled="!tabStore.hasUnsavedTabs">
              保存所有
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 右键菜单 -->
    <div
      v-show="showContextMenu"
      ref="contextMenuRef"
      class="context-menu"
      :style="contextMenuStyle"
      @click.stop
    >
      <div class="context-menu-content">
        <div 
          v-if="contextMenuTab?.closable !== false"
          class="context-menu-item" 
          @click="handleContextMenuCommand('close')"
        >
            <el-icon><Close /></el-icon>
          <span>关闭</span>
        </div>
        <div 
          class="context-menu-item" 
          :class="{ disabled: tabStore.tabs.length <= 1 }"
          @click="handleContextMenuCommand('closeOthers')"
        >
            <el-icon><Close /></el-icon>
          <span>关闭其他</span>
        </div>
        <div 
          class="context-menu-item" 
          :class="{ disabled: isLastTab(contextMenuTab) }"
          @click="handleContextMenuCommand('closeToRight')"
        >
            <el-icon><Right /></el-icon>
          <span>关闭右侧</span>
        </div>
        <div class="context-menu-divider"></div>
        <div 
          v-if="canDuplicate(contextMenuTab)"
          class="context-menu-item" 
          @click="handleContextMenuCommand('duplicate')"
        >
            <el-icon><CopyDocument /></el-icon>
          <span>复制标签页</span>
        </div>
        <div 
          class="context-menu-item" 
          @click="handleContextMenuCommand('rename')"
        >
            <el-icon><Edit /></el-icon>
          <span>重命名</span>
        </div>
      </div>
    </div>

    <!-- 新建标签页菜单 -->
    <div
      v-show="showNewTabMenu"
      ref="newTabMenuRef"
      class="context-menu"
      :style="newTabMenuStyle"
      @click.stop
    >
      <div class="context-menu-content">
        <div 
          class="context-menu-item" 
          :class="{ disabled: !hasActiveConnection }"
          @click="handleNewTabCommand('query')"
        >
            <el-icon><Document /></el-icon>
          <span>新建查询</span>
        </div>
        <div 
          class="context-menu-item" 
          :class="{ disabled: !hasActiveConnection }"
          @click="handleNewTabCommand('design')"
        >
            <el-icon><Edit /></el-icon>
          <span>设计表</span>
        </div>
      </div>
    </div>

    <!-- 重命名对话框 -->
    <el-dialog
      v-model="showRenameDialog"
      title="重命名标签页"
      width="400px"
      @close="cancelRename"
    >
      <el-input
        ref="renameInputRef"
        v-model="renameTitle"
        placeholder="请输入新的标签页名称"
        @keyup.enter="confirmRename"
      />
      <template #footer>
        <div class="space-x-2">
          <el-button @click="cancelRename">取消</el-button>
          <el-button type="primary" @click="confirmRename">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onUnmounted } from 'vue'
import { useTabStore, useConnectionStore } from '@/stores'

const tabStore = useTabStore()
const connectionStore = useConnectionStore()

// 响应式数据
const contextMenuRef = ref()
const contextMenuTab = ref(null)
const newTabMenuRef = ref()
const showRenameDialog = ref(false)
const renameInputRef = ref()
const renameTitle = ref('')
const renamingTab = ref(null)
const showContextMenu = ref(false)
const showNewTabMenu = ref(false)
const contextMenuStyle = ref({
  position: 'fixed',
  left: '0px',
  top: '0px',
  zIndex: 9999
})
const newTabMenuStyle = ref({
  position: 'fixed',
  left: '0px',
  top: '0px',
  zIndex: 9999
})

// 计算属性
const hasActiveConnection = computed(() => {
  return connectionStore.activeConnectionId !== null
})

// 方法
const getTabIcon = (tab) => {
  const iconMap = {
    query: 'Document',
    browse: 'View',
    design: 'Edit',
    connection: 'Link'
  }
  return iconMap[tab.type] || 'Document'
}

const getTabTooltip = (tab) => {
  let tooltip = tab.title
  
  if (tab.connectionId) {
    const connection = connectionStore.getConnection(tab.connectionId)
    if (connection) {
      tooltip += `\n连接: ${connection.name}`
    }
  }
  
  if (tab.database) {
    tooltip += `\n数据库: ${tab.database}`
  }
  
  if (tab.table) {
    tooltip += `\n表: ${tab.table}`
  }
  
  if (tab.unsaved) {
    tooltip += '\n(未保存)'
  }
  
  return tooltip
}

const setActiveTab = (tabId) => {
  tabStore.setActiveTab(tabId)
}

const closeTab = async (tabId) => {
  await tabStore.closeTab(tabId)
}

const handleTabContextMenu = (event, tab) => {
  event.preventDefault()
  event.stopPropagation()
  contextMenuTab.value = tab
  
  // 计算菜单位置
  const x = event.clientX
  const y = event.clientY
  
  // 获取视口尺寸
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight
  
  // 估算菜单尺寸
  const menuWidth = 160
  const menuHeight = 200
  
  // 调整位置以确保菜单在视口内
  let left = x + 2
  let top = y + 2
  
  if (left + menuWidth > viewportWidth) {
    left = x - menuWidth - 2
  }
  
  if (top + menuHeight > viewportHeight) {
    top = y - menuHeight - 2
  }
  
  // 确保菜单不会超出视口边界
  left = Math.max(4, Math.min(left, viewportWidth - menuWidth - 4))
  top = Math.max(4, Math.min(top, viewportHeight - menuHeight - 4))
  
  contextMenuStyle.value = {
    position: 'fixed',
    left: `${left}px`,
    top: `${top}px`,
    zIndex: 9999
  }
  
  showContextMenu.value = true
  
  // 添加全局点击事件监听器来关闭菜单
  nextTick(() => {
    document.addEventListener('click', hideContextMenu, { once: true })
    document.addEventListener('contextmenu', hideContextMenu, { once: true })
  })
}

const hideContextMenu = () => {
  showContextMenu.value = false
  contextMenuTab.value = null
}

const hideNewTabMenu = () => {
  showNewTabMenu.value = false
}

const handleContextMenuCommand = async (command) => {
  const tab = contextMenuTab.value
  if (!tab) return

  // 隐藏菜单
  hideContextMenu()

  // 检查是否禁用
  if (command === 'closeOthers' && tabStore.tabs.length <= 1) return
  if (command === 'closeToRight' && isLastTab(tab)) return

  switch (command) {
    case 'close':
      await closeTab(tab.id)
      break
    case 'closeOthers':
      await tabStore.closeOtherTabs(tab.id)
      break
    case 'closeToRight':
      await closeTabsToRight(tab)
      break
    case 'duplicate':
      tabStore.duplicateTab(tab.id)
      break
    case 'rename':
      startRename(tab)
      break
  }
}

const handleTabAction = async (command) => {
  switch (command) {
    case 'closeOthers':
      if (tabStore.activeTabId) {
        await tabStore.closeOtherTabs(tabStore.activeTabId)
      }
      break
    case 'closeAll':
      await tabStore.closeAllTabs()
      break
    case 'saveAll':
      await saveAllTabs()
      break
  }
}

const openNewTabMenu = (event) => {
  // 计算菜单位置
  const x = event.clientX
  const y = event.clientY
  
  // 获取视口尺寸
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight
  
  // 估算菜单尺寸
  const menuWidth = 160
  const menuHeight = 100
  
  // 调整位置以确保菜单在视口内
  let left = x + 2
  let top = y + 2
  
  if (left + menuWidth > viewportWidth) {
    left = x - menuWidth - 2
  }
  
  if (top + menuHeight > viewportHeight) {
    top = y - menuHeight - 2
  }
  
  // 确保菜单不会超出视口边界
  left = Math.max(4, Math.min(left, viewportWidth - menuWidth - 4))
  top = Math.max(4, Math.min(top, viewportHeight - menuHeight - 4))
  
  newTabMenuStyle.value = {
    position: 'fixed',
    left: `${left}px`,
    top: `${top}px`,
    zIndex: 9999
  }
  
  showNewTabMenu.value = true
  
  // 添加全局点击事件监听器来关闭菜单
  nextTick(() => {
    document.addEventListener('click', hideNewTabMenu, { once: true })
    document.addEventListener('contextmenu', hideNewTabMenu, { once: true })
  })
}

const handleNewTabCommand = (command) => {
  // 隐藏菜单
  hideNewTabMenu()

  // 检查是否禁用
  if (!hasActiveConnection.value) {
    ElMessage.warning('请先选择一个数据库连接')
    return
  }

  const connectionId = connectionStore.activeConnectionId

  switch (command) {
    case 'query':
      tabStore.createQueryTab(connectionId)
      break
    case 'design':
      // 需要选择数据库
      selectDatabaseForNewTable(connectionId)
      break
  }
}

const selectDatabaseForNewTable = async (connectionId) => {
  try {
    // 这里应该显示数据库选择对话框
    // 暂时使用默认数据库
    const connection = connectionStore.getConnection(connectionId)
    if (connection && connection.database) {
      tabStore.createDesignTab(connectionId, connection.database)
    } else {
      ElMessage.warning('请在连接配置中指定默认数据库')
    }
  } catch (error) {
    ElMessage.error('创建表设计器失败: ' + error.message)
  }
}

const isLastTab = (tab) => {
  if (!tab) return true
  const index = tabStore.tabs.findIndex(t => t.id === tab.id)
  return index === tabStore.tabs.length - 1
}

const canDuplicate = (tab) => {
  return tab && tab.type === 'query'
}

const closeTabsToRight = async (tab) => {
  const index = tabStore.tabs.findIndex(t => t.id === tab.id)
  if (index === -1) return
  
  const tabsToClose = tabStore.tabs.slice(index + 1)
  for (const tabToClose of tabsToClose) {
    await tabStore.closeTab(tabToClose.id)
  }
}

const saveAllTabs = async () => {
  // 这里应该实现保存所有标签页的逻辑
  // 暂时只是标记为已保存
  for (const tab of tabStore.unsavedTabs) {
    tabStore.markTabSaved(tab.id)
  }
  ElMessage.success('所有标签页已保存')
}

const startRename = (tab) => {
  renamingTab.value = tab
  renameTitle.value = tab.title
  showRenameDialog.value = true
  
  nextTick(() => {
    renameInputRef.value?.focus()
    renameInputRef.value?.select()
  })
}

const confirmRename = () => {
  if (!renamingTab.value || !renameTitle.value.trim()) {
    return
  }
  
  tabStore.renameTab(renamingTab.value.id, renameTitle.value.trim())
  cancelRename()
  ElMessage.success('标签页重命名成功')
}

const cancelRename = () => {
  showRenameDialog.value = false
  renamingTab.value = null
  renameTitle.value = ''
}

// 组件销毁时清理
onUnmounted(() => {
  hideContextMenu()
  hideNewTabMenu()
  document.removeEventListener('click', hideContextMenu)
  document.removeEventListener('contextmenu', hideContextMenu)
  document.removeEventListener('click', hideNewTabMenu)
  document.removeEventListener('contextmenu', hideNewTabMenu)
})
</script>

<style scoped>
.tab-header {
  height: 48px;
  user-select: none;
}

.tab-list {
  display: flex;
  align-items: center;
  height: 100%;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.tab-list::-webkit-scrollbar {
  display: none;
}

.tab-item {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 12px;
  margin: 4px 2px;
  background: #f5f7fa;
  border: 1px solid #e5e7eb;
  border-radius: 6px 6px 0 0;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  min-width: 120px;
  max-width: 200px;
  white-space: nowrap;
}

.tab-item:hover {
  background: #e5e7eb;
}

.tab-item.active {
  background: #ffffff;
  border-bottom-color: #ffffff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.tab-item.unsaved {
  font-style: italic;
}

.tab-icon {
  margin-right: 6px;
  font-size: 14px;
  flex-shrink: 0;
}

.tab-title {
  flex: 1;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unsaved-indicator {
  width: 6px;
  height: 6px;
  background: #f59e0b;
  border-radius: 50%;
  margin-left: 4px;
  flex-shrink: 0;
}

.tab-close {
  margin-left: 4px;
  padding: 2px !important;
  min-height: 16px !important;
  width: 16px !important;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.tab-item:hover .tab-close {
  opacity: 1;
}

.tab-close:hover {
  background: rgba(239, 68, 68, 0.1) !important;
  color: #ef4444 !important;
}

.new-tab-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin: 0 4px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  color: #6b7280;
}

.new-tab-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.tab-actions {
  border-left: 1px solid #e5e7eb;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  z-index: 9999;
  min-width: 160px;
  user-select: none;
  animation: contextMenuFadeIn 0.15s ease-out;
  transform-origin: top left;
}

@keyframes contextMenuFadeIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-4px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.context-menu-content {
  padding: 4px 0;
}

.context-menu-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  font-size: 13px;
  color: #374151;
  cursor: pointer;
  transition: background-color 0.15s ease;
  gap: 8px;
}

.context-menu-item:hover:not(.disabled) {
  background-color: #f3f4f6;
}

.context-menu-item.disabled {
  color: #9ca3af;
  cursor: not-allowed;
}

.context-menu-divider {
  height: 1px;
  background-color: #e5e7eb;
  margin: 4px 0;
}

.context-menu-item .el-icon {
  width: 16px;
  height: 16px;
  font-size: 14px;
}

.context-menu-item span {
  flex: 1;
}

.space-x-2 > * + * {
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tab-item {
    min-width: 100px;
    max-width: 150px;
  }
  
  .tab-title {
    font-size: 12px;
  }
}
</style> 